﻿
var menuEvents = function () {

    //** ** Variaveis globais ** **
    //Para o mouse over do scroll
    var desce;
    var sobe;

    //iframe em 100%
    $("iframe.iframeContent").attr("height", ($(window).height()) - 50); //

    $("img.Header").click(function () {
        MenuOpenClose();
    });

    //Controla o Abre e Fecha do menu
    MenuOpenClose = function (caller) {
        if ($("div.Corpo").is(":hidden")) {
            $("div.Corpo").slideDown("slow");
            $("img.Header").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/btn_menu_aberto.png";

            //redimensiona iframe
            dimensionaIframe("diminuir");

            //aparece com a busca
            $("div.BuscaMain").slideDown("slow");

            if ($("div.BreadCrumb").is(":hidden"))
                $("div.BreadCrumb").slideDown("slow");
        }
        else {
            if (caller != "breadcrumb") {
                $("div.Corpo").slideUp("slow");
                $("img.Header").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/btn_menu.png";

                //redimensiona iframe
                dimensionaIframe("aumentar");

                //some com a busca
                timerBusca = setTimeout(
                function () {
                    $("div.BuscaMain").slideUp("slow");
                },
            150);
            }
        }

    }

    $("img.MenuFechar").click(function () {
        $("div.Corpo").slideUp("slow");
        $("img.Header").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/btn_menu.png";

        //redimensiona iframe
        dimensionaIframe("aumentar");

        //some com a busca
        timerBusca = setTimeout(
                function () {
                    $("div.BuscaMain").slideUp("slow");
                },
            150);

    });

    //INICIO DOS EVENTOS DE FAVORITOS
    //aparece o favoritos
    $("img.btnFavoritos").click(function () {
        if ($("div.FavoritosMain").is(":hidden"))
            $("div.FavoritosMain").slideDown("slow");
        else
            $("div.FavoritosMain").slideUp("slow");
    });
    $("img.FavoritosFechar").click(function () {
        $("div.FavoritosMain").slideUp("slow");
    });

    //Clique em adicionar novo favorito, abre popup de cadastro
    $("div.FavoritosAdd").find("a").click(function () {
        var param = Math.random();
        window.showModalDialog(baseUrl + "Pages/Favoritos.aspx?param=" + param, "Favoritos", "dialogWidth:650px;dialogHeight:500px,target=_self")

    });

    //Clique no item favorito e exibicao da pagina
    $("div.itemFavorite").click(function () {
        var urlFavorite = $(this).attr("id");
        window.location = urlFavorite;
        $("img.FavoritosFechar").click();
        MenuOpenClose();
    });

    //Clique no item favorito(mais acessados) e exibicao da pagina    
    $("div.topFavoritoCategoria").click(function () {
        var topFavorite = $(this).attr("id");
        window.location = topFavorite;
        $("img.FavoritosFechar").click();
        MenuOpenClose();
    });

    //FIM DOS EVENTOS DE FAVORITOS

    //INICIO DOS EVENTOS DE ALERTAS  
    //Aparece menu alertas
    $("img.btnAlertas").click(function () {
        if ($("div.AlertsMain").is(":hidden"))
            $("div.AlertsMain").slideDown("slow");
        else
            $("div.AlertsMain").slideUp("slow");
    });

    //Abre cadastro de alertas
    $("img.addNewAlert").click(function () {
        var param = Math.random();
        window.showModalDialog(baseUrl + "Pages/Alerts.aspx?param=" + param, "Alertas", "dialogWidth:550px;dialogHeight:650px");
    });

    //Marcar todos os alertas
    function marcar() {
        var arrayAlert = $("div.alertCheck input");
        for (var i = 0; i < arrayAlert.length; i++) {
            $("div.alertCheck input:eq(" + i + ")").get(0).checked = true;
        }
    }

    //Demarcar todos os alertas
    function desmarcar() {
        var arrayAlert = $("div.alertCheck input");
        for (var i = 0; i < arrayAlert.length; i++) {
            $("div.alertCheck input:eq(" + i + ")").get(0).checked = false;
        }
    }

    //Selecionar todos os alertas
    $("input.markAll").click(function () {
        if ($("input.markAll").attr("checked") == true) {
            marcar();
        } else {
            desmarcar();
        }
    });

    //Abrir infomações do alerta
    alertInfo = function (divName) {

        var id = $(divName).children("span[class='renderId']").attr("innerText");
        var title = $(divName).children("span[class='renderTitulo']").attr("innerText");
        var description = $(divName).children("span[class='renderDesc']").attr("innerText");
        var link = $(divName).find("a").attr("href");

        $("label#infoId").attr("innerText", id);
        $("label#infoTitulo").attr("innerText", title);
        $("label#infoDescription").attr("innerText", description);
        $("a#infoLink").attr("href", link);
        $("a#infoLink").attr("innerText", link);
        $("div.alertInfoHide").addClass("alertInfoVisible");

        createAlertUser(id);
        $(divName).find("img").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/icon_readAlert.PNG";

    };

    //Fechar informações do alerta
    $("img.alertInfoFechar").click(function () {
        $("div.alertInfoHide").removeClass("alertInfoVisible");
        $("div.alertInfoHide").addClass("alertInfoHide");
    });


    //Deleta alertas
    $("img.deleteAlert").click(function () {
        $("div.msgAlertDiv").hide();
        var arrayAlert = $("div.alertCheck input");
        for (var i = 0; i < arrayAlert.length; i++) {
            var idAlert = $("div.alertCheck input:eq(" + i + ")").attr("class");
            
            if ($("div.alertCheck input:eq(" + i + ")").attr("checked") == true) {

                var itemPai = $("div.alertCheck input:eq(" + i + ")").attr("parentNode");
                var itemRoot = $(itemPai).attr("parentNode");

                if (arrayAlert.length <= "1") {
                    alert("Alerta " + idAlert + " será excluído.");
                }
                $(itemRoot).removeClass("alertLido");
                $(itemRoot).addClass("alertExcluido");

                $("div.alertCheck input:eq(" + i + ")").get(0).checked = false;

                $.ajax({
                    type: "POST",
                    url: baseUrl + "MenuService.asmx/deleteAlert",
                    data: { valor: idAlert },
                    async: true,
                    dataType: "json",
                    success: function (data, status) {
                    },
                    error: function (xhr) {
                    }
                });

            } else {
            }
        };
        newAlertImage();
    });


    //Marca como não lido
    $("img.notReadAlert").click(function () {

        var arrayAlert = ("div.alertCheck input");
        for (var i = 0; i < arrayAlert.length; i++) {
            var idAlert = $("div.alertCheck input:eq(" + i + ")").attr("class");
            if ($("div.alertCheck input:eq(" + i + ")").attr("checked") == true) {

                var itemPai = $("div.alertCheck input:eq(" + i + ")").attr("parentNode");
                var itemRoot = $(itemPai).attr("parentNode");
                var icone = $("div#" + idAlert).attr("firstChild");
                $(icone).get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/icon_notReadAlert.png";

                $.ajax({
                    type: "POST",
                    url: baseUrl + "MenuService.asmx/notRead",
                    data: { valor: idAlert },
                    async: true,
                    dataType: "json",
                    success: function (data, status) {
                    },
                    error: function (xhr) {
                    }
                });

            } else {
            }
        };

    });

    //Verifica novos alertas
    function newAlertFunction() {
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/CountNewAlert",
            data: "{q:''}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (data, status) {

                if (parseInt(data.d) > 0) {
                    $("img.btnAlertas").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/mensagemAnimado.gif";
                }
                else {
                    $("img.btnAlertas").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/icone_mensagem.png";
                }
                CarregaAlertRenderView();
            },
            error: function (xhr) {
            }
        });
    }

    //Fecha menu alertas
    $("img.AlertasFechar").click(function () {
        $("div.AlertsMain").slideUp("slow");
    });

    //Criar novo alerta
    function createAlertUser(id) {
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/CreateAlertUser",
            data: { idAlert: id }, //Parametro passado para o metodo.
            dataType: "xml",
            async: true,
            success: function (data, status) {
            },
            error: function (xhr) {
            }
        });
        newAlertImage();
    }

    //Altera icone de alertas se há itens novos
    function newAlertImage() {
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/CountNewAlert",
            data: "{q:''}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (data, status) {

                if (parseInt(data.d) > 0) {
                    $("img.btnAlertas").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/mensagemAnimado.gif";
                }
                else {
                    $("img.btnAlertas").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/icone_mensagem.png";
                }
            },
            error: function (xhr) {
            }
        });
    }

    //Timer para verificar novos alertas
    $("div.Timer").epiclock({
        mode: EC_LOOP,
        format: 'i:s {minutos para próxima solicitação.}',
        offset: { minutes: 2 },
        onTimer: newAlertFunction
    });

    $.epiclock();

    //FIM DOS EVENTOS DE ALERTAS


    //INICIO DOS EVENTOS DE BUSCA
    $("input.txtBusca").keypress(function (e) {
        if (e.which == 13) {
            MenuOpenClose();
            $("img.btnBusca").click();
            return false;

        }
    });

    //Clique na "lupa" de busca
    $("img.btnBusca").click(function () {
        var valor = $("input.txtBusca").attr("value");
        window.location = baseUrl + "Pages/Search.aspx?q=" + valor;
        //$("iframe.iframeContent").attr("src", baseUrl + "Pages/Search.aspx?q=" + valor);
        MenuOpenClose();

    });

    //FIM DOS EVENTOS DE BUSCA

    // ********* WaterMarker do TextBox de busca
    var watermark = "Busca por palavra chave";
    if ($(".txtBusca").val() == "") {
        $(".txtBusca").val(watermark);
        $(".txtBusca").addClass("txtBusca_watermarked");
    }
    $(".txtBusca").focus(function () {
        if (this.value == watermark) {
            this.value = "";
            $(this).removeClass("txtBusca_watermarked");
        }
    }).blur(function () {
        if (this.value == "") {
            this.value = watermark;
            $(this).addClass("txtBusca_watermarked");
        }
    });
    // ********* Fim WaterMarker do TextBox de busca



    //Funcao q eh chamada no load do MenuUserControl pra chamar as criacoes de menus.
    CarregaMenu = function () {


        var querystring = window.location.querystring;
        var _sistemaId = (querystring["sistemaId"]) ? querystring["sistemaId"] : 0;
        var _featureId = (querystring["featureId"]) ? querystring["featureId"] : 0;
        var _featureIdChild = (querystring["featureIdChild"]) ? querystring["featureIdChild"] : 0;

        CarregaRenderedView(_featureId, 0, _sistemaId, "Sistemas");
        CarregaRenderedView(_featureId, 0, _sistemaId, "FeaturesA");
        DisplayMenuItens(_featureId, 0, _sistemaId);

        CarregaAlertRenderView();


        if (_sistemaId > 0) {
            $("div.MenuSistemasItem").removeClass("MenuSistemasItemSelecionado");
            $("div.MenuFeaturesAItem").removeClass("MenuFeaturesAItemSelecionado");
            $("div.BreadCrumb").slideDown("fast");
        }
        //        $("input#sistemaId").attr("value", _sistemaId);
        //        $("input#featureId").attr("value", _featureId);
        $("span." + _sistemaId).parent().addClass("MenuSistemasItemSelecionado");
        $("div.MenuFeaturesAItensContainer div:nth-child(2)").addClass("MenuFeaturesAItemSelecionado");
        CarregaRenderedView(_featureId, _featureIdChild, _sistemaId, "BreadCrumb");
    }

    //Seta as mudancas de estilo para o item selecionado *GENERICO*
    ChangeClassSelectedItem = function (_this) {
        var myClass = $(_this).attr("class");
        //remove a class de selecao de todos

        $("div." + myClass).removeClass(myClass + "Selecionado");
        //em _this add a classe selecionada
        $(_this).addClass(myClass + "Selecionado");

        //Salva id do item selecionado pra poder manter o estado no post
        if (myClass == "MenuSistemasItem")
            sistemaId = $(_this).attr("id");
        if (myClass == "MenuFeaturesItem")
            moduloId = $(_this).attr("id");


    }

    window.location.querystring = (function () {

        var collection = {};
        var querystring = window.location.search;

        if (!querystring) {
            return { toString: function () { return ""; } };
        }

        querystring = decodeURI(querystring.substring(1));

        // Carregar a chave e valor para o retorno na coleção.
        var pairs = querystring.split("&");

        for (var i = 0; i < pairs.length; i++) {
            if (!pairs[i]) {
                continue;
            }

            // Usando o  split("=") para pegar os valores
            var seperatorPosition = pairs[i].indexOf("=");

            if (seperatorPosition == -1) {
                collection[pairs[i]] = "";
            }

            else {
                collection[pairs[i].substring(0, seperatorPosition)]
                = pairs[i].substr(seperatorPosition + 1);
            }
        }

        // toString() returns the key/value pairs concatenated
        collection.toString = function () {
            return "?" + querystring;
        };
        return collection;
    })();


    CarregaAlertRenderView = function () {
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/GetRenderedView",
            data: { featureId: 0, featureIdChild: 0, sistemaId: 0, viewPath: "Controls/AlertUserControl.ascx" }, //Parametro passado para o metodo caso vá fazer filtro.
            dataType: "xml",
            async: true,
            success: function (data, status) {
                $(data).find('string').each(function () {
                    $("div.AlertMenu").html($(this).text());
                });
            },
            error: function (xhr) {
                $("div.AlertMenu").html(xhr.status + " - " + xhr.statusText + "<br/><br/> Ocorreu um erro ao tentar carregar o controle.");
            }
        });
    }

    // *********  Carrega o usercontrol chamando um Servico
    CarregaRenderedView = function (featureId, featureIdChild, sistemaId, control, retry) {

        var _featureId = featureId;
        var _featureIdChild = featureIdChild;
        var _sistemaId = sistemaId;
        var _control = control;
        var _retry = retry;
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/GetRenderedView",
            data: { featureId: featureId, featureIdChild: featureIdChild, sistemaId: sistemaId, viewPath: "Controls/" + control + "UserControl.ascx" }, //Parametro passado para o metodo caso vá fazer filtro.
            dataType: "xml",
            async: false,
            success: function (data, status) {
                $(data).find('string').each(function () {
                    $("div.Menu" + control + "Itens").html($(this).text());
                });

                //Verifica quem é o item pra atribuir os eventos
                if (control == "Sistemas")
                    LoadSistemasEvents(control);
                if (control == "FeaturesA")
                    LoadFeaturesAEvents(control);
                if (control == "FeaturesB")
                    LoadFeaturesBEvents(control);
                if (control == "BreadCrumb")
                    LoadBreadCrumbEvents(control);
            },
            error: function (xhr) {

                if (!_retry)
                    CarregaRenderedView(_featureId, _featureIdChild, _sistemaId, _control, true);
                else
                    $("div.Menu" + control + "Itens").html(xhr.status + " - " + xhr.statusText + "<br/><br/> Ocorreu um erro ao tentar carregar o controle.");
            }
        });
    }
    // *********  Carrega o usercontrol "FeatureB"
    DisplayMenuItens = function (featureId, featureIdChild, sistemaId, retry) {

        var _featureId = featureId;
        var _featureIdChild = featureIdChild;
        var _sistemaId = sistemaId;
        var _retry = retry;
        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/GetRenderedViewMenuItens",
            data: { featureId: featureId, featureIdChild: featureIdChild, sistemaId: sistemaId, currentPage: currentPage, displayWidth: $(window).width() }, //Parametro passado para o metodo caso vá fazer filtro.
            dataType: "xml",
            async: true,
            success: function (data, status) {
                $(data).find('string').each(function () {
                    $("div.FeaturesMenuItem").html($(this).text());
                });
                LoadFeaturesBEvents();
            },
            error: function (xhr) {
                if (!retry)
                    DisplayMenuItens(_featureId, _featureIdChild, _sistemaId, true);
                else
                    $("div.FeaturesMenuItem").html(xhr.status + " - " + xhr.statusText + "<br/><br/> Ocorreu um erro ao tentar carregar o controle.");
            },
            complete: function (xhr) {
                //carrega o breadcrumb apenas se eh a primeira vez que ele esta sendo chamdo
                if (sistemaId == 0) {
                    setTimeout(function () {
                        var s = $("div.MenuSistemasItensContainer div:nth-child(2)").children(0).attr("class");
                        var a = $("div.MenuFeaturesAItensContainer div:nth-child(2)").children(0).attr("class");

                        CarregaRenderedView(a, 0, s, "BreadCrumb");
                    }, 100);
                }
            }
        });
    }

    //Carrega todos os eventos do menu Sistemas.
    LoadSistemasEvents = function (control) {

        //Conta o numero de filhos que um elemento tem
        var ctSistemas = $('div.MenuSistemasItensContainer').children().size();
        $("img.MenuSistemasScrollDown").unbind("click").click(function () {
            if (allHiddenSistemas < (ctSistemas - 6)) { // 5 é o numero de elementos que tem que aparecer na tela + 1 do elemento fake q tenho pra equilibrar.
                $("div.MenuSistemasItensContainer div:nth-child(" + (allHiddenSistemas) + ")").hide();
                allHiddenSistemas++;
            }
        });
        //mouse over
        $("img.MenuSistemasScrollDown").unbind("mouseover").mouseover(function () {
            //com o set interval vamos a cada 400ms fazer o up dos itens
            desce =
            setInterval(function () {
                if (allHiddenSistemas < (ctSistemas - 6)) { // 5 é o numero de elementos que tem que aparecer na tela + 1 do elemento fake q tenho pra equilibrar.
                    $("div.MenuSistemasItensContainer div:nth-child(" + (allHiddenSistemas) + ")").slideUp("slow");
                    allHiddenSistemas++;
                }
            }, 400);
        });
        //mouse out
        $("img.MenuSistemasScrollDown").unbind("mouseout").mouseout(function () {
            clearInterval(desce);
        });
        $("img.MenuSistemasScrollUp").unbind("click").click(function () {
            if (allHiddenSistemas > 1) {
                allHiddenSistemas--;
                $("div.MenuSistemasItensContainer div:nth-child(" + (allHiddenSistemas) + ")").show();
            }
        });
        //mouse over
        $("img.MenuSistemasScrollUp").unbind("mouseover").mouseover(function () {
            //com o set interval vamos a cada 400ms fazer o up dos itens
            sobe =
            setInterval(function () {
                if (allHiddenSistemas > 1) {
                    allHiddenSistemas--;
                    $("div.MenuSistemasItensContainer div:nth-child(" + (allHiddenSistemas) + ")").slideDown("slow");
                }
            }, 400);
        });
        //mouse out
        $("img.MenuSistemasScrollUp").unbind("mouseout").mouseout(function () {
            clearInterval(sobe);
        });

        //se eh a primeira vez o campo hidden eh zero por padrao
        if ($("input#sistemaId").attr("value") == "0") {
            //Primeiro item selecionado
            var querystring = window.location.querystring;
            var itemSelecionado = (querystring["sistemaId"]) ? querystring["sistemaId"] : $("div.MenuSistemasItensContainer div:nth-child(2)").children(0).attr("class");
            $("div.MenuSistemasItensContainer div:nth-child(2)").addClass("MenuSistemasItemSelecionado");
            $("input#sistemaId").attr("value", itemSelecionado);

        }
        else {
            var sistemaId = $("input#sistemaId").attr("value");
            //recupera o item que estava selecionado se nao eh zero
            $("span." + sistemaId).parent().addClass("MenuSistemasItemSelecionado");
        }

        //** Itens do menu quando selecionados **
        $("div.MenuSistemasItem").unbind("click").click(function () {
            currentPage = 0;
            //remove a class de selecao de todos
            $("div.MenuSistemasItem").removeClass("MenuSistemasItemSelecionado");
            //em mim add a classe selecionada
            $(this).addClass("MenuSistemasItemSelecionado");

            var id = $(this).children(0).attr("class");
            $("input#sistemaId").attr("value", id);

            //recarrega os controles
            CarregaRenderedView(0, 0, id, "FeaturesA");
            //CarregaRenderedView(0, 0, id, "FeaturesB");
            DisplayMenuItens(0, 0, id);
            CarregaRenderedView(0, 0, id, "BreadCrumb");


        });

    }

    // ********* Fim da carga do usercontrol de Sistemas

    // ********* Carrega o usercontrol de FeaturesA
    LoadFeaturesAEvents = function (control) {
        //** Menu Features **
        allHiddenFeatures = 1;

        //Conta o numero de filhos que um elemento tem
        var ctModulo = $('div.MenuFeaturesAItensContainer').children().size();

        $("img.MenuFeaturesAScrollDown").unbind("click").click(function () {
            if (allHiddenFeatures < (ctModulo - 6)) { // 7 é o numero de elementos que tem que aparecer na tela + 1 do elemento fake q tenho pra equilibrar.
                $("div.MenuFeaturesAItensContainer div:nth-child(" + (allHiddenFeatures) + ")").hide();
                allHiddenFeatures++;
            }
        });

        //mouse over
        $("img.MenuFeaturesAScrollDown").unbind("mouseover").mouseover(function () {
            //com o set interval vamos a cada 400ms fazer o up dos itens
            desce =
            setInterval(function () {
                if (allHiddenFeatures < (ctModulo - 6)) { // 7 é o numero de elementos que tem que aparecer na tela + 1 do elemento fake q tenho pra equilibrar.
                    $("div.MenuFeaturesAItensContainer div:nth-child(" + (allHiddenFeatures) + ")").slideUp("slow");
                    allHiddenFeatures++;
                }
            }, 400);
        });
        //mouse out
        $("img.MenuFeaturesAScrollDown").unbind("mouseout").mouseout(function () {
            clearInterval(desce);
        });
        $("img.MenuFeaturesAScrollUp").unbind("click").click(function () {
            if (allHiddenFeatures > 1) {
                allHiddenFeatures--;
                $("div.MenuFeaturesAItensContainer div:nth-child(" + (allHiddenFeatures) + ")").show();
            }
        });

        //mouse over
        $("img.MenuFeaturesAScrollUp").unbind("mouseover").mouseover(function () {
            //com o set interval vamos a cada 400ms fazer o up dos itens
            sobe =
        setInterval(function () {
            if (allHiddenFeatures > 1) {
                allHiddenFeatures--;
                $("div.MenuFeaturesAItensContainer div:nth-child(" + (allHiddenFeatures) + ")").slideDown("slow");
            }
        }, 400);
        });
        //mouse out
        $("img.MenuFeaturesAScrollUp").unbind("mouseout").mouseout(function () {
            clearInterval(sobe);
        });

        //Primeiro item selecionado
        $("div.MenuFeaturesAItensContainer div:nth-child(2)").addClass("MenuFeaturesAItemSelecionado");
        //se for a primeira vez que carrega ele salva o id do item selecionado.
        $("input#featureId").attr("value", $("div.MenuFeaturesAItensContainer div:nth-child(2)").children().attr("class"));

        //e o titulo do Feature B == ao item selecionado de Feature A

        //** Itens do menu quando selecionados **
        $("div.MenuFeaturesAItem").unbind("click").click(function () {

            currentPage = 0;
            //remove a class de selecao de todos
            $("div.MenuFeaturesAItem").removeClass("MenuFeaturesAItemSelecionado");
            //em mim add a classe selecionada
            $(this).addClass("MenuFeaturesAItemSelecionado");

            var id = $(this).children(0).attr("class");

            $("input#featureId").attr("value", id);
            var sistemaId = $("input#sistemaId").attr("value");

            //recarrega os controles
            DisplayMenuItens(id, 0, sistemaId);
            CarregaRenderedView(id, 0, sistemaId, "BreadCrumb");

        });
    }
    // ********* Fim da carga do usercontrol de FeaturesA

    // ********* Carrega do usercontrol de FeaturesB

    LoadFeaturesBEvents = function () {
        var featureId = $("input#featureId").attr("value");
        var sysId = $("input#sistemaId").attr("value");

        var id;

        //** AQUI ** EVENTO CLICK EM QUALQUER ITEM DO FEATUREB(MODULOS DE ITENS, OS DE CAIXINHA DA ESQUERDA)
        $("div.MenuFeatureBCorpo").unbind("click").click(function () {
            var thisClass = $(this).attr("class");
            //ponho a selecao
            //remove a class de selecao de todos
            $("div.MenuFeatureBCorpo").removeClass("MenuFeatureBCorpoSelecionado");
            //em mim add a classe selecionada
            $(this).addClass("MenuFeatureBCorpoSelecionado");

            //Salva id do item selecionado pra poder manter o estado no post
            moduloId = $(this).attr("id");

            id = $(this).children(0).attr("class");
            //uso a class do this pra poder pegar seu filho a que contem o link, assim pego a url do item realmente clicado.

            //verifica se o item do menu é um link 
            var ehLink = ($(this).children("a").is("[href$=.aspx#]") || $(this).children("a").is("[href$=.aspx]") || $(this).children("a").is("[href^=http://]") || $(this).children("a").is("[href^=javascript:]") || $(this).children("a").is("[href*=.aspx?]") || $(this).children("a").is("[href*=.asp?]") || $(this).children("a").is("[href$=.html]"));
            var querystring = window.location.querystring;

            if (sysId == 0)
                sysId = (querystring["sistemaId"]) ? querystring["sistemaId"] : 0;

            var url = $(this).children("a").attr("href");
            var urlCompleta;

            if ($(this).children("a").is("[href$=.aspx]"))
                urlCompleta = url + "?sistemaId=" + sysId + "&featureId=" + featureId + "&featureIdChild=" + id;
            else
                urlCompleta = url;

            if (!ehLink) {
                CarregaRenderedView(featureId, id, sysId, "FeaturesA");
                DisplayMenuItens(featureId, id, sysId);
                CarregaRenderedView(featureId, id, sysId, "BreadCrumb");
            }
            else {

                CarregaRenderedView(featureId, id, sysId, "BreadCrumb");
                window.location = urlCompleta;
                //Da mesma maneira de cima eu pego a Description e e escrevo no titulo.
                $("div.TituloPagina").text($(this).text());
                setVisit($(this).attr("innerText"), url, id);
                MenuOpenClose();
            }

        });

        //Titulo do Feature B
        $("span.FeaturesTitulo").text(
            $("div.MenuFeaturesAItemSelecionado").text()
        );

        //Setas de paginacao
        $("span.imgFeaturesetaEsq").unbind("click").click(function () {
            currentPage--;
            DisplayMenuItens(featureId, 0, sysId);
        });

        $("span.imgFeaturesetaDir").unbind("click").click(function () {
            currentPage++;
            DisplayMenuItens(featureId, 0, sysId);
        });

        //Botao Voltar
        $("span.BotaoVoltar").unbind("click").click(function () {

            //Numero de itens do BreadCumb
            var tamanho = $("div.MenuBreadCrumbItens a").length;
            var penultimo = tamanho - 1

            //Clique no penultimo item do BreadCumb
            $("div.MenuBreadCrumbItens a:nth-child(" + penultimo + ")").click();

            if (tamanho == 2) {

                $("img.imgVoltar").get(0).src = baseUrl + "App_Themes/InfraWebTheme/images/voltarDisable.png"
            }

        });

    }

    // ********* Fim da carga do usercontrol de FeaturesB
    LoadBreadCrumbEvents = function () {
        //Clique em qualquer item do breadCrumb
        $("div.MenuBreadCrumbItens").find("a").unbind("click").click(function () {
            currentPage = 0;
            if ($(this))
                var featureId = $(this).attr("id");
            var sistemaId = $("input#sistemaId").attr("value");
            if (sistemaId == 0)
                sistemaId = (querystring["sistemaId"]) ? querystring["sistemaId"] : 0;
            if (featureId == 0)
                featureId = (querystring["featureId"]) ? querystring["sistemaId"] : 0;


            //verifica se o link que tem neste item é finalizado com .aspx e retorna um bool
            var ehLink = $(this).is("[href$=#]");
            if (!ehLink) {
                CarregaRenderedView(featureId, 0, sistemaId, "Sistemas");
                CarregaRenderedView(featureId, 0, sistemaId, "FeaturesA");

                DisplayMenuItens(featureId, 0, sistemaId);
                CarregaRenderedView(featureId, 0, sistemaId, "BreadCrumb");
                //Abre o menu
                MenuOpenClose("breadcrumb");
            } else {
                MenuOpenClose();
            }
        });

    }



    //Redimensiona o iframe conforme expande ou nao o menu
    dimensionaIframe = function (acao) {

        if (acao == "diminuir") {
            //250 é o espaco que o menu ocupa junto com o bread crumb na tela. 550 é o tempo da animacao
            $("iframe.iframeContent").animate({ height: $(window).height() - 250 }, 550);
        }
        else {
            //50 é o espaco que o menu ocupa quando fechado na tela. 550 é o tempo da animacao
            $("iframe.iframeContent").animate({ height: $(window).height() - 50 }, 550);
        }
    }
    //***********Autocomplete do TextBox de Busca
    FindMenus = function () {
        getMenus = function () {
            $.ajax({
                type: "POST",
                url: baseUrl + "MenuService.asmx/GetMenus",
                data: "{q:''}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (data, status) {
                    $.each(data, function (i, item) {
                        var tmpItens = item.toString().split(',');
                        var aItems = '';
                        var aFeatureIds = '';
                        var aFeatureParentIds = '';
                        var aSystemIds = '';
                        var aIsLastFeatures = '';

                        for (var j = 0; j < tmpItens.length - 1; j++) {
                            var all = tmpItens[j].split('|');
                            aItems = aItems + all[0] + ',';
                            aFeatureIds = aFeatureIds + all[1] + ',';
                            aSystemIds = aSystemIds + all[2] + ',';
                            aFeatureParentIds = aFeatureParentIds + all[3] + ',';
                            aIsLastFeatures = aIsLastFeatures + all[4] + ',';
                        }
                        itens = aItems.substring(0, aItems.length - 1).split(',');
                        $("input#allDescriptions").attr("value", aItems.substring(0, aItems.length - 1));
                        $("input#allSystems").attr("value", aSystemIds.substring(0, aSystemIds.toString().length - 1));
                        $("input#allFeatures").attr("value", aFeatureIds.substring(0, aFeatureIds.toString().length - 1));
                        $("input#allFeaturesParent").attr("value", aFeatureParentIds.substring(0, aFeatureParentIds.toString().length - 1));
                        $("input#allIsLastFeatures").attr("value", aIsLastFeatures.substring(0, aIsLastFeatures.toString().length - 1));
                    });
                },
                error: function (xhr) {
                }
            });
            return itens;
        }
        var itens = getMenus();

        $("input.txtBusca").autocomplete({
            lookup: itens,
            width: 300,
            delimiter: /(,|;)\s*/,
            onSelect: function (value, data) {
                var allDescs = $("input#allDescriptions").attr("value").split(',');
                var systemIds = $("input#allSystems").attr("value").split(',');
                var featureIds = $("input#allFeatures").attr("value").split(',');
                var featureParentIds = $("input#allFeaturesParent").attr("value").split(',');
                var isLastFeature = $("input#allIsLastFeatures").attr("value").split(',');

                for (var j = 0; j < allDescs.length - 1; j++) {
                    if (value == allDescs[j]) {
                        goSelect(value, systemIds[j], featureIds[j], featureParentIds[j], isLastFeature[j]);
                    }
                }
            }
        });
    }
    //***********Fim do Autocomplete do TextBox de Busca

    goSelect = function (itemSelected, systemId, featureId, featureParentId, isLastFeature) {

        //remove a class de selecao de todos
        $("div.MenuSistemasItem").removeClass("MenuSistemasItemSelecionado");

        //em mim add a classe selecionada
        $(this).addClass("MenuSistemasItemSelecionado");
        $("input#sistemaId").attr("value", systemId);

        $("div.MenuFeatureBCorpo").removeClass("MenuFeatureBCorpoSelecionado");
        //em mim add a classe selecionada
        $("MenuFeatureB").addClass("MenuFeatureBCorpoSelecionado");
        $("input#featureId").attr("value", featureId);


        if (isLastFeature == 0) {
            CarregaRenderedView(featureParentId, 0, systemId, "Sistemas");
            CarregaRenderedView(featureParentId, 0, systemId, "FeaturesA");
            DisplayMenuItens(featureParentId, 0, systemId);
            CarregaRenderedView(featureParentId, featureId, systemId, "BreadCrumb");

            $("span." + featureId).click();

        } else {
            CarregaRenderedView(featureId, 0, systemId, "Sistemas");
            CarregaRenderedView(featureId, 0, systemId, "FeaturesA");
            CarregaRenderedView(featureId, 0, systemId, "FeaturesB");
            DisplayMenuItens(featureId, 0, systemId);
            CarregaRenderedView(featureId, 0, systemId, "BreadCrumb");
        }

    }
}
//***************Script de favoritos***************//

function setVisit(nameFeature, url, idFeature) {
    var now = new Date();
    fixDate(now);
    var feature = "feature"
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    var visits = getCookie(feature + "|" + nameFeature.toString() + "|" + url.toString() + "|" + idFeature.toString());
    if (visits >= 1) {
        visits = parseInt(visits) + 1;
    } else {
        visits = 1;
    }
    var nameAlter = clearCaractereAcento(nameFeature.toString());
    setCookie(feature + "|" + nameAlter.toString() + "|" + url.toString() + "|" + idFeature.toString(), visits, now);
}

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function getCookie(name) {
    cookies = document.cookie.split(";");
    for (var i = 0, im = cookies.length; im > i; i++) {
        var cookieName = TrimString(cookies[i].split("=")[0]);
        if (cookieName == name) {
            return cookies[i].split("=")[1]
        };
    };
}
function fixDate(date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

function clearCaractereAcento(text) {
    text = text.replace(new RegExp('[ÁÀÂÃ]', 'gi'), 'a');
    text = text.replace(new RegExp('[ÉÈÊ]', 'gi'), 'e');
    text = text.replace(new RegExp('[ÍÌÎ]', 'gi'), 'i');
    text = text.replace(new RegExp('[ÓÒÔÕ]', 'gi'), 'o');
    text = text.replace(new RegExp('[ÚÙÛ]', 'gi'), 'u');
    text = text.replace(new RegExp('[Ç]', 'gi'), 'c');
    return text;
}
function TrimString(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}
///////////////////////////////////////////////////Busca
var eventosAlertsWindow = function () {
    closeWindow = function () {
        window.close();
    };
}

var eventosBusca = function () {

    //Gera thumbnail ao repousar o mouse
    $("a.searchPageName").mouseenter(function () {
        $("img.resultThumbnail").attr("src", baseUrl + "App_Themes/InfraWebTheme/images/loadThumbnail.gif");

        document.getElementById('resultThumbnail').style.left = window.event.clientX + 40;
        document.getElementById('resultThumbnail').style.top = window.event.clientY - 50;

        $("img.resultThumbnail").addClass("resultThumbnailVisible");
        $("img.resultThumbnail").fadeIn(1000);

        var urlPage = $(this).attr("href");
        thumbnailAddress = setTimeout(function () { getThumbnail(urlPage) }, 1500);

    });

    //Oculta o thumbnail ao remover o mouse
    $("a.searchPageName").mouseleave(function () {
        $("img.resultThumbnail").fadeOut(1000);
        clearTimeout(thumbnailAddress);
    });

    function getThumbnail(urlPage) {
        var pageThumbnail;

        $.ajax({
            type: "POST",
            url: baseUrl + "MenuService.asmx/getThumbnail",
            data: { urlReceive: urlPage },
            async: false,
            success: function (data, status) {
                pageThumbnail = baseUrl + data.text;
            },
            error: function (xhr) {
            }
        });

        $("img.resultThumbnail").attr("src", pageThumbnail);
        $("img.resultThumbnail").addClass("resultThumbnailVisible");

        $("img.resultThumbnail").fadeIn(1000);
    };
};

//Carrega Evento para fim da sessão.
var SessionEndFunction = function () {
    $.ajax({
        type: "POST",
        url: baseUrl + "MenuService.asmx/AbandonSession",
        data: "{q:''}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function (data, status) {
        },
        error: function (xhr) {

        }
    });
};

var eventosFavoritos = function () {

    closeWindow = function () {
        window.close();
    }

    autocompleteLinks = function () {
        FindLinks = function () {

            $.ajax({
                type: "POST",
                url: baseUrl + "MenuService.asmx/GetLinks",
                data: "{q:''}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (data, status) {

                    $.each(data, function (i, link) {
                        var tmpLinks = link.toString().split(',');
                        var aLinkDescriptions = '';
                        var aLinkIds = '';
                        var aLinkUris = '';
                        var aLinkParentDesc = '';
                        var aLinkParentIds = '';

                        for (var j = 0; j < tmpLinks.length - 1; j++) {
                            var allLinks = tmpLinks[j].split('|');
                            aLinkDescriptions = aLinkDescriptions + allLinks[0] + ',';
                            aLinkIds = aLinkIds + allLinks[1] + ',';
                            aLinkUris = aLinkUris + allLinks[2] + ',';
                            aLinkParentDesc = aLinkParentDesc + allLinks[3] + ',';
                            aLinkParentIds = aLinkParentIds + allLinks[4] + ',';
                        }
                        linksDescriptions = aLinkDescriptions.substring(0, aLinkDescriptions.length - 1).split(',');
                        $("input#linkDescriptions").attr("value", aLinkDescriptions.substring(0, aLinkDescriptions.length - 1));
                        $("input#linkIds").attr("value", aLinkIds.substring(0, aLinkIds.toString().length - 1));
                        $("input#linkUris").attr("value", aLinkUris.substring(0, aLinkUris.toString().length - 1));
                        $("input#linkParentDescriptions").attr("value", aLinkParentDesc.substring(0, aLinkParentDesc.toString().length - 1));
                        $("input#linkParentIds").attr("value", aLinkParentIds.substring(0, aLinkParentIds.toString().length - 1));

                    });
                },
                error: function (xhr) {
                    alert('Erro ao processar o serviço');
                }
            });
            var returnLinks = linksDescriptions;
            return returnLinks;
        }

        var globalLinks = FindLinks();


        $("input.txtBuscaLink").autocomplete({
            lookup: globalLinks,
            width: 300,
            delimiter: /(,|;)\s*/,
            onSelect: function (value, data) {
                var allDescriptions = $("input#linkDescriptions").attr("value").split(',');
                var allLinkIds = $("input#linkIds").attr("value").split(',');
                var alllinkUris = $("input#linkUris").attr("value").split(',');
                var allParentDescriptions = $("input#linkParentDescriptions").attr("value").split(',');
                var allParentIds = $("input#linkParentIds").attr("value").split(',');

                for (var j = 0; j < allDescriptions.length - 1; j++) {
                    if (value == allDescriptions[j]) {
                        //enviaParametros(allDescriptions[j], allLinkIds[j], alllinkUris[j], allParentDescriptions[j], allParentIds[j]);
                        $("#txtNomeFavorito").attr("value", allDescriptions[j]);
                        $("label.lblUrl").attr("innerText", alllinkUris[j]);
                        $("#hiddenUrl").attr("value", alllinkUris[j]);
                    }
                }
            }
        });
    }
}


